Text and String Formatting Tutorial - some examples

This notebook demonstrates how to make nicely formatted numbers and tables in Python 3 (the version of Python we're using in class.)

Some useful references (which are the source of all of the information in this tutorial) are:

Note that the first part of this tutorial shows how to format numbers, and the last part shows how to add new lines, tabs, and special characters in Python.

Number Formatting

The following table shows various ways to format numbers using python's str.format() method. Examples include both float and integer formatting.

To run examples use this syntax:

print("FORMAT".format(NUMBER))

So, to get the output of the first example shown in the table below, you would run:

print("{:.2f}".format(3.1415926))

Note: If you can't see this table, you can find it at https://mkaz.tech/python-string-format.html

string.format() basics

Here are a couple of example of basic string substitution. The {} (i.e., "curly brackets") are the placeholder for the substituted variables. If no format is specified, it will insert and format the variables as a string. Note that you can have multiple variables in the print statement - just make sure you have the same number of pairs of brackets as you do variables in the format statement!


In [ ]:
s1 = "so much depends upon {}".format("a red wheel barrow")
s2 = "glazed with {} water beside the {} chickens".format("rain", "white")
print(s1)
print(s2)

You can also use the numeric position of the variables and change them in the strings. This gives some flexibility when doing the formatting - if you made a mistake in the order you can easily correct without shuffling all variables around. Note that you start counting from zero, just like in lists and arrays!


In [ ]:
s1 = " {0} are better than {1} ".format("dogs", "cats")
s2 = " {1} are better than {0} ".format("dogs", "cats")
print(s1)
print(s2)

Reuse Same Variable Multiple Times

The .format() method allows you to put them in any order as we saw above in the basics, but also allows for reuse.


In [ ]:
s1 = "Oh {0}, {0}! wherefore art thou {0}?".format("Romeo")
print(s1)

It's generally helpful to make sure you have the same number of {} as variables as arguments. For example, the following line of code will not work, since there are more sets of brackets than arguments to the format function and there aren't zeros in all of the brackets to indicate that the variable should be reused.


In [ ]:
s1 = "{} {}".format("testing")

Named Arguments

You can also use the new string format as a templating engine and use named arguments, instead of requiring a strict order.


In [ ]:
madlib = " I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table")
print(madlib)

Padding and Aligning Strings

By default values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be "padded" to a specific length. The number in the brackets tells Python what the minimum length of the string should be: if the number is smaller than the length of the string given, it'll print the entire string.


In [ ]:
s1 = "--{:10}--".format("test") #added dashes to see where the spaces are between them.
s2 = "--{:10}--".format("long test string")
print(s1)
print(s2)

By default, strings will left align, so the words will be on the left side of the resulting string. Integers and floats will right align by default. To enforce one alignment or another, you can add '>', '<', or '^'. The character should "point" in the direction of alignment (ex: '>' means right alignment, '^' means center alignment).


In [ ]:
s1 = "--{:10}--".format("test") #added dashes to see where the spaces are between them.
s2 = "--{:10}--".format(14)
print(s1)
print(s2)
print()

s1 = "--{:>10}--".format("test") #added dashes to see where the spaces are between them.
s2 = "--{:<10}--".format(14)
print(s1)
print(s2)
print()

s1 = "--{:^10}--".format("test") #added dashes to see where the spaces are between them.
s2 = "--{:^10}--".format(14)
print(s1)
print(s2)

Adding tabs and blank lines

An additional way to add space to print statements is to use special print comments called "escape sequences." The two most common (and most useful) of these are:

\n     add a new line (go to the next line)
\t     add a horizontal tab (several spaces)

In [ ]:
print("on the first line\non a second line")

In [ ]:
print("these\tare\tseparated\tby\ttabs")

These can be combined with the string formatting described above to make nicely-formatted tables. For example:


In [ ]:
for i in range(0,101,10):
    print("{}\t{:2e}\t{:2f}\twoo!".format(i,10**i,i/10))

Including special characters in print statements

When it comes to strings, Python interprets the backslash character () and single and double quotations (' and ") to mean special things. So how do you include these characters in strings? You add an additioanl backslash in front of them! For example:


In [ ]:
print("so I said \"hi, mom!\" and she waved at me.")

In [ ]:
print("this looks like a newline: \\n, but it doesn't go to a new line!")